package com.demo.collector.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.collector.enity.User;
import com.demo.collector.mapper.LoginMapper;
import com.demo.collector.util.result.JsonResult;
import com.demo.collector.util.security.HashUtil;
import com.demo.collector.util.security.RandUtil;

import com.demo.collector.util.security.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 沈伟峰
 */
@RestController
@CrossOrigin
public class LoginController {
    @Autowired
    private LoginMapper loginMapper;
    @CrossOrigin
    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
    public JsonResult checkPassword(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String userName = jsonObject.getString("username");

        String password = jsonObject.getString("password");
        String salt=loginMapper.getSalt(userName);
        String ps=HashUtil.hashPassword(password,salt);
        int flag=loginMapper.checkPassword(userName,HashUtil.hashPassword(password,salt));
        if(flag==1){
            int id=loginMapper.getId(userName);
            String token=TokenUtil.generateToken(id,userName);
            return JsonResult.Builder.builder().data(token).build();
        }else{
            return JsonResult.Builder.fail(0,"login failed");
        }


    }

    @CrossOrigin
    @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "application/json")
    public JsonResult register(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        Map<String, Object> map = new HashMap<>();
        String userName = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        String salt= RandUtil.getSalt();
        User user=new User();
        user.setAge(jsonObject.getInteger("age"));
        user.setUsername(userName);
        user.setPassword(HashUtil.hashPassword(password,salt));
        user.setSalt(salt);

        String sex = jsonObject.getString("sex");
        if (sex.length() == 2) {
            if (sex.equals("男性")) {
                user.setSex("f");
            } else if (sex.equals("女性")) {
                user.setSex("m");
            }
        } else {
            user.setSex("x");
        }

        loginMapper.addUser(user);
        return JsonResult.Builder.success("update succese","");
    }


}
